/**
 * 
 */
package any.desktop.gwt.client.ui;

import any.gwt.client.http.AsynClientEvent;
import any.gwt.client.http.AsynClientListener;
import any.gwt.client.util.DispacherContainer;
import any.gwt.client.util.DispatchEvent;
import any.gwt.client.util.DispatcherListener;

import com.allen_sauer.gwt.log.client.Log;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;

/**
 * TODO: Doc me
 * 
 * @author keke <keke@codehaus.org>
 * @version
 * @revision $Revision:$
 */
public class SearchView extends Composite implements AsynClientListener,
        DispatcherListener {
    private final FlowPanel outer;

    public SearchView() {
        super();
        DispacherContainer.getGlobalDispatcher().addDispatcherListener(this);
        outer = new FlowPanel();
        initWidget(outer);
        setStyleName("view");
        addStyleName("search");
    }

    public void fireDispatchEvent(final DispatchEvent event) {
        if (event.isConsumed()) {
            return;
        }
        if (event.getName().equals("searchResult")) {
            updateResults((JSONObject) event.getContent());
        }
    }

    public void fireEvent(final AsynClientEvent event) {
        if (event.getName().equals("search")) {
            updateResults(JSONParser.parse(event.getResponse().getText())
                    .isObject());
        }
    }

    protected void onUnload() {
        super.onUnload();
        DispacherContainer.getGlobalDispatcher().removeDispatcherListener(this);
    }

    protected void updateResults(final JSONObject resultSet) {
        if (Log.isDebugEnabled()) {
            Log.debug("To update Results");
        }

        final JSONArray results = resultSet.get("results").isArray();
        outer.clear();
        for (int i = 0; i < results.size(); i++) {
            final SearchResultBox resultBox = new SearchResultBox(results
                    .get(i).isObject(), null);
            DeferredCommand.addCommand(new Command() {
                public void execute() {
                    outer.add(resultBox);
                }
            });
        }
    }
}
